package com.ruoyi.web.controller.app;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.app.domain.bo.*;
import com.ruoyi.app.domain.vo.*;
import com.ruoyi.app.service.*;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.FileUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.domain.SysOss;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * APP用户自动注册
 *
 * @author heike
 * @date 2025-12-08
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/autoRegister")
public class AppAutoRegisterController extends BaseController {

    private final IAppUserService iAppUserService;
    private final IAppSchoolService iAppSchoolService;
    private final IAppOccupationService iAppOccupationService;
    private final ISysOssService iSysOssService;
    private final IAppCityDistService iAppCityDistService;
    private final IAppUserImageService iAppUserImageService;
    private final IAppAssetService iAppAssetService;
    private final IAppUserSettingService iAppUserSettingService;
    private final IAppUserNameService iAppUserNameService;
    private final IAppLabelService iAppLabelService;
    private final IAppLabelLikeService iAppLabelLikeService;

    /**
     * 批量APP用户注册
     */
    @SaCheckPermission("system:autoRegister:add")
    @RepeatSubmit()
    @PostMapping()
    public R<String> add(@RequestBody AppAutoRegisterBo registerBo) {
        int count = registerBo.getNumber() * 10;
        int start = random(1, 10);
        String url = "http://wallpaper.apc.360.cn/index.php?c=WallPaper&a=getAppsByCategory&cid=" + registerBo.getImageType() + "&start=" + start + "&count=" + count + "&from=360chrome";
        String data = HttpUtils.sendGet(url);
        JSONObject parse = JSON.parseObject(data);
        JSONArray imageArray = parse.getJSONArray("data");
        ArrayList<String> images = new ArrayList<>();
        for (int i = 0; i < imageArray.size(); i++) {
            images.add(imageArray.getJSONObject(i).get("img_1024_768").toString());
        }
        AppUserBo appUserBo = new AppUserBo();
        appUserBo.setRegister("1");
        List<AppUserVo> appUserVos = iAppUserService.queryListOrder(appUserBo);
        Long number = null;
        if (appUserVos.size() > 0) {
            number = Long.valueOf(appUserVos.get(0).getUserName());
        } else {
            number = 20000000000L;
        }
        int max = images.size() - 1;
        //学校列表
        AppSchoolBo appSchoolBo = new AppSchoolBo();
        appSchoolBo.setStatus(Constants.SUCCESS);
        List<AppSchoolVo> schools = iAppSchoolService.queryList(appSchoolBo);

        //职业列表
        AppOccupationBo occupationBo = new AppOccupationBo();
        occupationBo.setStatus(Constants.SUCCESS);
        List<AppOccupationVo> occupations = iAppOccupationService.queryList(occupationBo);

        //地址列表
        List<AppCityDistVo> appCityDistVos = iAppCityDistService.queryList();

        //昵称列表
        List<AppUserNameVo> userNameVos = iAppUserNameService.queryList(new AppUserNameBo());
        for (int i = 1; i <= registerBo.getNumber(); i++) {
            number = number + 1;
            String userName = String.valueOf(number);
            AppUserBo user = new AppUserBo();
            int age = random(registerBo.getAgeMin(), registerBo.getAgeMax());
            Calendar instance = Calendar.getInstance();
            instance.setTime(new Date());
            instance.add(Calendar.YEAR, -1 * age);
            user.setBirthday(instance.getTime().getTime());
            user.setUserName(userName);
            user.setPhone(userName);
            AppUserNameVo nickNameVo = userNameVos.get(random(0, userNameVos.size() - 1));
            user.setNickName(nickNameVo.getName());
            user.setStatus(UserStatus.OK.getCode());
            user.setSignature("一瓶水认识一个有趣的人");
            //密码:123456789
            user.setPassword(BCrypt.hashpw("25f9e794323b453885f5181f1b624d0b"));
            user.setHeight(String.valueOf(random(registerBo.getHeightMin(), registerBo.getHeightMax())));

            AppSchoolVo school = schools.get(random(0, schools.size() - 1));
            user.setSchool(school.getName());

            AppOccupationVo occupation = occupations.get(random(0, occupations.size() - 1));
            user.setOccupation(occupation.getName());


            AppCityDistVo appCityDistVo = appCityDistVos.get(random(0, appCityDistVos.size() - 1));
            user.setProvince(appCityDistVo.getProvinceId().toString());
            user.setCity(appCityDistVo.getId().toString());

            if ("2".equals(registerBo.getSex())) {
                user.setSex(String.valueOf(random(0, 1)));
            } else {
                user.setSex(registerBo.getSex());
            }
            user.setTarget("0");
            user.setTargetStatus("0");
            user.setRegister("1");
            user.setCreateTime(DateUtils.getNowDate());

            String avatar = images.get(random(0, max));
            SysOss ossAvatar = iSysOssService.upload(FileUtils.uploadImgUrlToMultipartFile(avatar));
            user.setAvatar(ossAvatar.getUrl());
            user.setPhoto(ossAvatar.getUrl());
            iAppUserService.insertByBo(user);
            //创建用户后操作
            if (user.getId() != null) {
                for (int j = 0; j < 3; j++) {
                    SysOss useImage = iSysOssService.upload(FileUtils.uploadImgUrlToMultipartFile(images.get(random(0, max))));
                    AppUserImageBo appUserImageBo = new AppUserImageBo();
                    appUserImageBo.setUserId(user.getId());
                    appUserImageBo.setImage(useImage.getUrl());
                    iAppUserImageService.insertByBo(appUserImageBo);
                }
                List<AppLabelVo> list = iAppLabelService.queryList(new AppLabelBo());
                HashSet<Long> labels = new HashSet<>();
                for (AppLabelVo k : list) {
                    labels.add(list.get(random(0, list.size() - 1)).getId());
                    if (labels.size() >= 3) {
                        break;
                    }
                }
                labels.forEach(e -> {
                    AppLabelVo label = iAppLabelService.queryById(e);
                    AppLabelLikeBo labelLikeBo = new AppLabelLikeBo();
                    labelLikeBo.setUserId(user.getId());
                    labelLikeBo.setLabelId(label.getId());
                    labelLikeBo.setTypeId(label.getTypeId());
                    labelLikeBo.setLikeStatus(Constants.FAIL);
                    labelLikeBo.setStatus(Constants.SUCCESS);
                    iAppLabelLikeService.insertByBo(labelLikeBo);
                });
                HashMap<String, String> map = new HashMap<>(2);
                map.put("nickname", user.getNickName());
                map.put("avatarurl", avatar);
                AppAssetVo appAsset = iAppAssetService.queryByUid(user.getId());
                if (Objects.isNull(appAsset)) {
                    AppAssetBo appAssetBo = new AppAssetBo();
                    appAssetBo.setUserId(user.getId());
                    iAppAssetService.insertByBo(appAssetBo);
                }
                AppUserSettingVo settingVo = iAppUserSettingService.queryByUserId(user.getId());
                if (Objects.isNull(settingVo)) {
                    iAppUserSettingService.insert(user.getId());
                }
                AppUserBo userBo = new AppUserBo();
                userBo.setAvatar(ossAvatar.getUrl());
                userBo.setId(user.getId());
                iAppUserService.updateByBo(userBo);
            }
        }
        return R.ok("注册成功");
    }

    /**
     * 获取一个随机数
     *
     * @param min
     * @param max
     * @return
     */
    private int random(int min, int max) {
        return min + (int) (Math.random() * (max - min + 1));
    }

}
